<?php

namespace App\Service;

use App\Entity\Book;
use App\Entity\Plan;
use App\Repository\BookRepository;
use App\Repository\PlanRepository;
use App\Util\CustomException\ParamErrorException;
use App\Vo\PageVo;

class BookService
{
    private BookRepository $bookRepository;
    private PlanRepository $planRepository;

    public function __construct(BookRepository $bookRepository,PlanRepository $planRepository)
    {
        $this->bookRepository = $bookRepository;
        $this->planRepository = $planRepository;
    }

    /**
     * 分页查询所有未删除、未被下架的图书
     */
    public function findBookList(string $searchContent = "", int $page = 1,int $userId = 0): PageVo
    {
        // 查询
        $paginator = $this->bookRepository->findBookList($searchContent, $page);
        $count = $paginator->count();

        $plans = null;
        // 设置图书阅读状态
        if ($userId!==0){
            $plans = $this->planRepository->findBy(['userId' => $userId]);
        }
        return new PageVo($count, DEFAULT_SIZE, $page, $paginator,$plans);
    }

    /**
     * @throws ParamErrorException
     */
    public function saveBook(Book $book): bool
    {
        // 查询是否已经存在
        if ($this->bookRepository->findOneBy(["bookTitle" => $book->getBookTitle(), "bookAuthor" => $book->getBookAuthor()]) !== null) {
            throw new ParamErrorException("The book already exists");
        }
        return $this->bookRepository->save($book,true);
    }
}